package com.ruoyi.web.ydz.util.areaUtil;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Objects;

@Component
public class AreaUtil {

    public HashMap getClientIp(HttpServletRequest request) {

        HashMap<String,Object> responseMap = new HashMap();

        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        responseMap.put("ip",ipAddress);
        responseMap.put("area","未知");

        if (StringUtils.isEmpty(ipAddress)){
            String locationInfo = AreaUtil.getLocationInfo(ipAddress);
            if (StringUtils.isEmpty(locationInfo)){
                JSONObject jsonObject = JSON.parseObject(locationInfo);
                if (!Objects.isNull(jsonObject)){

                    if (!Objects.isNull(jsonObject.get("city"))){
                        responseMap.put("area",jsonObject.get("city"));
                    } else if (!Objects.isNull(jsonObject.get("regionName"))) {
                        responseMap.put("area",jsonObject.get("regionName"));
                    }else if (!Objects.isNull(jsonObject.get("country"))){
                        responseMap.put("area",jsonObject.get("country"));
                    }else{
                        responseMap.put("area",jsonObject.get("未知"));
                    }

                }
            }
        }


        return responseMap;
    }

    public static String getLocationInfo(String ip) {
        String apiUrl = "http://ip-api.com/json/" + ip + "?lang=zh-CN";
        try {
            URL url = new URL(apiUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            return response.toString(); // 返回JSON格式的地理位置信息
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
